var global_targetObj;

$(document).ready(function(){
	$(document).click(function(){
		$('#__suggest-panel_popup').html("");
		$("#__suggest-panel_popup").hide("fast");
	});
	
	$("#__suggest-panel_popup").on('click', "#__suggest-panel_popup_item", function(){
		var item_id = $(this).children(".__suggest-panel_popup_item_id").text();
		var item_name = $(this).children(".__suggest-panel_popup_item_name").text();
			
		global_targetObj.value = item_name + " <" + item_id + ">";
		$(global_targetObj).focus();
	});
});

$(document).mousemove(function(e) {
    window.mousePosX = e.pageX;
    window.mousePosY = e.pageY;
});

function loadSuggest(targetOutputObj, contentType){
	global_targetObj = targetOutputObj;
	var text = targetOutputObj.value;
	
	if (text.length > 0) {
		$.getJSON("script/loadSuggest.php", {"text": text, "type": contentType}, function(data) {
			if (data.status === 'success') {
				var str = "";
				$.each(data.suggest, function(key, val){
					str += "<div id = '__suggest-panel_popup_item'>";
					str += "<span class = '__suggest-panel_popup_item_id' style = 'display:none;'>" + val.id + "</span>";
					$.each(data.suggest[key], function(prop, prop_val) {
						// price of product
						if (prop !== "id" && prop !== "price") {
							if (prop.indexOf("name") !== -1) {
								str += "<span class = '__suggest-panel_popup_item_name' style = 'display:none;'>" + prop_val + "</span>";
								str += "<b>" + prop_val + "</b><br>";
							} else {
								if (contentType == "product" && prop == "quantity") {
									if (prop_val > 0) {
										str += "<b>Số lượng:</b> " + prop_val + "<br>";
									} else {
										str += "<b>Hết hàng</b><br>";
									}
								} else {
									str += prop_val + "<br>";
								}
							}
						}
					});
					
					str += "</div>";
				});
				if (str === "") {
					$('#__suggest-panel_popup').html("");
					$("#__suggest-panel_popup").hide("fast");
				} else {
					$('#__suggest-panel_popup').html(str);
					$("#__suggest-panel_popup").show("fast");
				}
			} else {
				$('#__suggest-panel_popup').html(data.message);
				$("#__suggest-panel_popup").show("fast");
			}
		});
		$("#__suggest-panel_popup").css("top", mousePosY);
		$("#__suggest-panel_popup").css("left", mousePosX);
	} else {
		$('#__suggest-panel_popup').html("");
		$("#__suggest-panel_popup").hide("fast");
	}
}

